<template>
   <view>

	<uni-fab :pattern="pattern" horizontal="right" vertical="bottom" direction="vertical"  @fabClick="fabClick"></uni-fab>
    <!-- <scroll-view scroll-y class="page" @scrolltolower="onScrollToBottom"> -->
        <!-- <uni-section title="卡片标题+额外信息" type="line"> -->
		<view>
			<uni-card v-for="(item, index) in newsList" :key="index" :title="item.name" :margin="setMargin(index)"  :extra="item.shop_id" style="display: flex;" @tap="goToMenu(item.name, item.shop_id)">
				<text>{{item.shop_desc}}</text>
			</uni-card>
			 
			<view  class="loading">{{loadingText}}</view>
		</view>
		
        <!-- </uni-section> -->
   <!-- </scroll-view> -->
   	<!-- 输入框示例 -->
   	<uni-popup ref="inputDialog" type="dialog">
   		<uni-popup-dialog ref="inputClose"  title="推荐餐厅" value="对话框预置提示内容!"
   			 @confirm="dialogInputConfirm">
			<uni-forms ref="baseForm" :rules="customRules"  :modelValue="formData">
				<uni-forms-item label="餐厅名称" required>
					<uni-easyinput v-model="formData.name"  placeholder="请输入餐厅名称" />
				</uni-forms-item>
				<uni-forms-item label="餐厅地址" required><!-- 后面优化直接通过地图点获取地理位置，及定位获取-->
					<uni-easyinput v-model="formData.address" placeholder="请输入餐厅地址" />
				</uni-forms-item>
				<uni-forms-item label="餐厅简介">
					<uni-easyinput type="textarea" v-model="formData.desc" placeholder="请输入餐厅简介" />
				</uni-forms-item>
			</uni-forms>
			</uni-popup-dialog>
   	</uni-popup>
   </view>
</template>

<script>
const db = uniCloud.database(); 
var _self, page = 1, timer = null;
export default {
    name: 'shops',
    data() {
        return {
			newsList: [],
			loadingText: '加载中...',
			pageSize: 1, //页数
			pageCurrent: 10, // 页数大小
			pattern: {
				color: "#ff0",
				selectedColor: "#00f",
				backgroundColor: "#fff",
				buttonColor: "#00aa7f"
			},
			customRules: {
				name: {
					rules: [{
						required: true,
						errorMessage: '餐厅名称不能空'
					}]
				},
				address: [{
					rules: [{
						required: true,
						errorMessage: '地址不能空'
					}]
				}]
			},
			formData: {
				name: '',
				address: '',
				desc: '',
			},
			content: [
				{iconPath: "/static/api.png",selectedIconPath: "/static/apiHL.png", text:"新加餐厅", active: false} 
			],
        }
    },
    onLoad() {
      _self = this;
      uni.startPullDownRefresh();
      // this.getnewsList();
    },
    onPullDownRefresh() {
      this.pageSize = 1;
      uni.showNavigationBarLoading();
      this.getData("shop");
    },
    onReachBottom() {
		console.error("????++",this.pageSize);
		_self.loadingText = '加载中...';
	    uni.showNavigationBarLoading();
	    this.getData("shop");
		
    },
    methods:{
		setMargin(index){
			if((index + 1) === this.newsList.length) { //最后一个
				return '10px 10px 10px 10px'
			}else {
				return  '10px 10px 0px 10px'
			}
		},
		dialogInputConfirm() {
            console.log("?ee------>",this.formData)
			// this.formData = {};
            this.addData()
			// this.$refs.inputDialog.close()
		},
		fabClick(e) {
			this.$refs.inputDialog.open()
		},
		dialogClose() {
			console.log('点击关闭')
		},
		goToMenu(name, id) {
           uni.navigateTo({
           	    url: '/pages/menu/main?navTitle=' + name + '&dishId=' + id,
                events: { //为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
                    acceptDataFromOpenedPage: function (data) {
                       console.log("????????========>>",data);
                    },
                    someEvent: function(data) {
                        console.log("????????=======？？？？？？？？？==>",data);
                    }
                },
                success: (res) => {
                   // res.eventChannel.emit('acceptDataFromOpenedPage', { data: 'de1111' })
                }
           })
		},
        // getmorenews() {
        //  if(_self.loadingText != '' && _self.loadingText != '加载更多') {
        //     return false;
        //  }
        //  _self.loadingText = '加载中...';
        //  uni.showNavigationBarLoading();
        //  var tt = setTimeout(() => {
        //     _self.loadingText = '';   
        //     var _d = ["444","555","666"]; //模拟获取到的数据
        //     if(_d == null){  
        //       uni.hideNavigationBarLoading();  
        //       _self.loadingText = '已加载全部';
        //       return false;
        //     }
        //     page++; //判断是否还有页数
        //     _self.newsList = _self.newsList.concat(_d); //添加在尾部
        //     _self.loadingText = '加载更多'; //设置下一次显示的内容
        //     uni.hideNavigationBarLoading();
        //  }, 3000);
        //  // uni.request({
        //  //    url: 'https://demo.hcoder.net/index.php?user=hcoder&pwd=hcoder&m=list1&page='+page,
        //  //    method: 'GET',
        //  //    success: function(res){
        //  //     _self.loadingText = '';
        //  //     if(res.data == null){
        //  //      uni.hideNavigationBarLoading();
        //  //      _self.loadingText = '已加载全部';
        //  //      return false;
        //  //     }
        //  //     page++;
        //  //     console.log(res);
        //  //     _self.newsList = _self.newsList.concat(res.data.split('--hcSplitor--'));
        //  //     _self.loadingText = '加载更多';
        //  //     uni.hideNavigationBarLoading();
        //  //    }
        //  //   });
        // },
        getnewsList : function(){

           // let ti = setTimeout(() =>{
           //    page++;
           //    _self.newsList = ['111','222','333','444','555'];
           //    uni.hideNavigationBarLoading();
           //    uni.stopPullDownRefresh();
           //    _self.loadingText = '加载更多';
           //    clearTimeout(ti);
           // }, 2000);
           // uni.request({
           //  url: 'https://demo.hcoder.net/index.php?user=hcoder&pwd=hcoder&m=list1&page=1',
           //  method: 'GET',
           //  success: function(res){
           //   page++;
           //   _self.newsList = res.data.split('--hcSplitor--');
           //   uni.hideNavigationBarLoading();
           //   uni.stopPullDownRefresh();
           //   _self.loadingText = '加载更多';
           //  }
           // });
        }, 
     //    onScrollToBottom() {
     //      console.log("??啛啛喳喳错错错错错???")
	    // },
		async getData(tableName) {
			// uni.showLoading({
			// 	mask: true
			// })
			let res = await db.collection(tableName)
			.skip((this.pageSize - 1) * this.pageCurrent)
			.limit(this.pageCurrent)
			.get()
			if(this.pageSize === 1) {
				this.newsList = res.result.data;
			}else {
				let _newList = [...this.newsList];
				this.newsList = _newList.concat(res.result.data); //添加在尾部
			}
			// uni.hideLoading()
			uni.hideNavigationBarLoading()
			uni.stopPullDownRefresh()
			if(this.newsList.length >= 10){
				_self.pageSize++;
				_self.loadingText = '加载更多';
			}else {
				_self.loadingText = '已加载全部';
			}

			
			// return res.result.data
		},
		async addData() {
			uni.showLoading({
				mask: true,
				title: "加载中..."
			})
			await uniCloud.callFunction({
				name: "addShop",
				data: {
					create_date: Date.now(),
					name: "鱼胶饭店铺2",
					shop_desc: "这家吃鱼饭的2",
					shop_address: "官塘公交车站2"
				}
			}).then((res) =>{
				uni.hideLoading()
				uni.showModal({
					content: "添加成功",
					showCancel: false
				});
                uni.startPullDownRefresh();
			}).catch( err =>{
				uni.hideLoading()
				uni.showModal({
					content: "添加数据失败",
					showCancel: false
				})
				console.error(err)
			})
			//  await db.collection(tableName).add({
			// 	data: {
			// 		create_date: Date.now(),
			// 		name: "鱼胶饭店铺",
			// 		shop_id: "FTT001"
			// 	}
			// }).then(res =>{
			// 	console.error("查看内容====>", res.result);
			// 	uni.hideLoading()
			// })
		}
		
    },
    
}
</script>

<style>
 
::v-deep .uni-card {
	margin:  10px;
}
/* .newslist{padding:10px; line-height:60px; font-size:28px;} */
.loading{text-align:center; height: 50px; line-height:50px;}
.page {
	/* position: relative; */
    height: calc(100vh);
    background-color: #00CE47;
}
</style>
